package com.wx.myatomikos.config;


import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * @ClassName DataSourceOneConfig
 * @Author wx
 * @Description 数据源-1配置
 * @Date 2018-12-27-21:56
 */
@Configuration
@MapperScan(basePackages = "com.wx.myatomikos.dao*",  sqlSessionTemplateRef = "oneSqlSessionTemplate")
public class DataSourceOneConfig {


    /**
     * @methodName: oneDataSource
     * @author: wx
     * @description: 注入数据源-1
     * @param 
     * @date: 2018/12/27
     * @return: javax.sql.DataSource
     */
    @Primary
    @Bean(name = "oneDataSource")
    public DataSource oneDataSource(@Qualifier(value = "dBConfig1") DBConfig1 config1) throws SQLException {
        DruidXADataSource dataSource = new DruidXADataSource();
        BeanUtils.copyProperties(config1,dataSource);
        // 将本地事务注册到创 Atomikos全局事务
        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(dataSource);
        xaDataSource.setUniqueResourceName("oneDataSource");
        xaDataSource.setTestQuery("SELECT 1 FROM DUAL");
        return xaDataSource;

    }
    
    /**
     * @methodName: oneSqlSessionFactory
     * @author: wx
     * @description: 创建工厂
     * @param dataSource
     * @date: 2018/12/27
     * @return: org.apache.ibatis.session.SqlSessionFactory
     */
    @Bean(name = "oneSqlSessionFactory")
    public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.wx.myatomikos.entity");
        bean.setDataSource(dataSource);
        return bean.getObject();

    }

    /**
     * @methodName: oneSqlSessionTemplate
     * @author: wx
     * @description: 创建模板
     * @param sqlSessionFactory
     * @date: 2018/12/27
     * @return: org.mybatis.spring.SqlSessionTemplate
     */
    @Bean(name = "oneSqlSessionTemplate")
    public SqlSessionTemplate oneSqlSessionTemplate(@Qualifier("oneSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
